▍程式碼
<style>
/* 收藏按鈕的基礎樣式 */
.favorite-btn {
cursor: pointer;
border: none;
background: none;
padding: 0;
color: #ccc; /* 預設顏色: 灰色 (未收藏) */
transition: color 0.2s;
outline: none;
vertical-align: top; /* 使圖標與文字對齊 */
margin-right: 5px;
}
/* 收藏後的樣式 */
.favorite-btn.favorited {
color: #ffc107; /* 收藏顏色: 金黃色 */
}
/* 星星圖標的 SVG 樣式 */
.star-icon {
width: 20px;
height: 20px;
}
</style>
<div>
{% for result in results %}
<div class="all_questions" data-question-data='{{ (result | default({}) ) | tojson }}' data-question-index="{{ loop.index0 }}">
<p>
<!-- 收藏按鈕 -->
<button class="favorite-btn{% if result.is_favorite %} favorited{% endif %}" onclick="toggleFavorite(this, event)">
<!-- 預設顯示空心星,點擊切換顏色 -->
<svg class="star-icon" viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z" />
</svg>
</button>
<strong>題目:</strong> {{ result.question_text }}
</p>
<div class="question-info">
來源:
{% for source in result.source_filename %}
<a href={{ source_path }} / {{ source }} target="_blank">{{ source }}</a>
{% endfor %}
{{ result.book_source }} p.{{ result.page_number }}
</div>
<ul class="list-unstyled">
{% set labels = ['A', 'B', 'C', 'D'] %}
{% for option in result.options %}
{% if option == result.answer %}
<li class="answer_highlight">({{ labels[loop.index0] }}) {{ option }}</li>
{% else %}
<li>({{ labels[loop.index0] }}) {{ option }}</li>
{% endif %}
{% endfor %}
</ul>
</div>
{% endfor %}
</div>
# views.py
@app.route('/toggle_favorite', methods=['POST'])
def toggle_favorite():
question_data = request.get_json()
client_question_data = request.get_json()
match_key = {
'question_text': client_question_data.get('question_text'),
'answer': client_question_data.get('answer'),
}
if not all(match_key.values()):
return jsonify({"error": "缺少匹配題目所需的關鍵欄位 (question_text 或 answer)"}), 400
all_questions = KNOWLEDGE_BASE
try:
found = False
new_favorite_state = False
# 尋找並切配題目的收藏狀態
for question in all_questions:
if (question.get('question_text') == match_key['question_text'] and
question.get('answer') == match_key['answer']):
# 取得或初始化收藏狀態,並進行切換
current_state = question.get('is_favorite', False)
new_favorite_state = not current_state
question['is_favorite'] = new_favorite_state
found = True
break
if not found:
return jsonify({"error": "找不到匹配的題目進行更新"}), 404
# 更新收藏狀態
with open(json_path, 'w', encoding='utf-8') as f:
json.dump(all_questions, f, ensure_ascii=False, indent=4)
action = "收藏" if new_favorite_state else "取消收藏"
return jsonify({
"success": True,
"message": f"{action}成功",
"is_favorite": new_favorite_state
}), 200
except FileNotFoundError:
return jsonify({"error": f"JSON 檔案未找到), 500
except json.JSONDecodeError:
return jsonify({"error": "JSON 檔案格式錯誤,無法解析"}), 500
except Exception as e:
print(f"處理錯誤: {e}")
return jsonify({"error": f"伺服器內部錯誤: {e}"}), 500
return jsonify({"message": "收藏狀態已更新", "question": question_data})